import { getRequest } from  './api'

export const initMenu = (router, store) => {
    //判断Vuex中是否有路由了
    if(store.state.routes.length > 0) return

    getRequest('/system/menu').then(res => {
        if (res){
            //格式好的路由
            let fmtRouters = formatRoutes(res);

            //添加路由
            router.addRoutes(fmtRouters)

            //将路由存入Vuex
            store.commit('initRoutes', fmtRouters)
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = []
    routes.forEach(router => {
        //获取请求中的路由相关信息
        let {
            path,
            component,
            name,
            iconCls,
            children,
        } = router;

        //遍历子路由
        if (children && children instanceof Array){
            //递归路由
            children = formatRoutes(children)
        }

        //封装路由
        let fmtRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve){
                if (component.startsWith('Home')){
                    require(['../views/' + component + '.vue'], resolve)
                 //根据组件名称分文件名处理每个文件下的组件路径
                }else if (component.startsWith('Emp')){
                    require(['../views/emp/' + component + '.vue'], resolve)
                } else if(component.startsWith('Per')){
                    require(['../views/per/' + component + '.vue'], resolve)
                } else if(component.startsWith('Sal')){
                    require(['../views/sal/' + component + '.vue'], resolve)
                } else if(component.startsWith('Sta')){
                    require(['../views/sta/' + component + '.vue'], resolve)
                } else if(component.startsWith('Sys')){
                    require(['../views/sys/' + component + '.vue'], resolve)
                }
            }
        }

        fmtRoutes.push(fmtRouter)
    })
    //返回封装处理好的路由信息
    return fmtRoutes
}
